/**
 * User: alesj
 * Date: 15.1.2006
 * Time: 15:37:13
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blueberry.spring.lotto.impl;

import com.alesj.blueberry.spring.parsing.*;

import java.math.BigInteger;
import java.util.Set;
import java.util.TreeSet;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
public class SimpleParser implements Parser {

    private int minNumbers;
    private int maxNumbers;
    private int maxValue;

    public SimpleParser(int minNumbers, int maxNumbers, int maxValue) {
        this.minNumbers = minNumbers;
        this.maxNumbers = maxNumbers;
        this.maxValue = maxValue;
    }

    public Map<String, Object> parse(String message) throws ParseException {
        String[] numbers = message.split(" ");
        Set<Integer> values = new TreeSet<Integer>();
        BigInteger result = BigInteger.valueOf(0);
        for(String number : numbers) {
            int value = Integer.parseInt(number);
            if (value <= 0 || value > maxValue) {
                throw new ValueParseException(value);
            }
            result = result.setBit(value);
            values.add(value);
        }
        int length = values.size();
        if (length < minNumbers || length > maxNumbers) {
            throw new LengthParseException(length);
        }
        // fill results 
        Map<String, Object> resultMap = new TreeMap<String, Object>();
        resultMap.put("values", values);
        resultMap.put("result", result);
        resultMap.put("duplicate", numbers.length - length);
        return resultMap;
    }

}
